package com.api.action;

import com.api.MEnumError;
import com.api.anno.ApiUnCheck;
import com.api.view.account.OauthMobileInfo;
import com.api.view.account.SmsCode;
import com.api.view.home.UserInfo;
import com.base.Const;
import com.base.MYjyConstant;
import com.base.MYjyEnmu;
import com.base.api.ApiBaseController;
import com.base.api.ApiException;
import com.base.api.MobileInfo;
import com.base.api.annotation.ApiMethod;
import com.base.api.sms.SmsCache;
import com.base.api.sms.SmsError;
import com.base.dao.model.Ret;
import com.base.oauthLogin.OauthLoginUtil;
import com.base.oauthLogin.model.OauthUserInfo;
import com.base.service.BFileService;
import com.base.support.LogKit;
import com.base.support.PropertySupport;
import com.base.util.IPUtil;
import com.base.util.StringUtil;
import com.item.dao.model.User;
import com.item.dao.model.UserExample;
import com.item.dao.model.UserOauth;
import com.item.dao.model.UserOauthExample;
import com.item.service.MobileVerifyService;
import com.item.service.SmsSendLogService;
import com.item.service.UserOauthService;
import com.item.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/api/account", produces = { "application/json;charset=UTF-8" })
@Api(tags = "账号登陆/注册")
public class ApiLoginController extends ApiBaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private MobileVerifyService verifyService;
	@Autowired
	private SmsSendLogService smsSendLogService;
	@Autowired
	private UserOauthService oauthService;
	@Autowired
	private BFileService fileService;


	public enum MobileMsgEnum {
		REGIST(1), FORGET(2), LOGIN(3);
		private int code;

		MobileMsgEnum(int code) {
			this.code = code;
		}

		public int getCode() {
			return this.code;
		}
		
		public String getPhone(String phone){
			return phone+Const.SEP+this.name();
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param phone
	 *            手机号
	 * @param type
	 *            1:注册,绑定手机 2:忘记密码
	 */
	@ApiOperation(value = "获取验证码", notes = "不需要登录<br/>测试阶段直接取返回的code,不发送短信")
	@RequestMapping(value = "/getMobileMsg", method = RequestMethod.POST)
	@ApiMethod(isAuth = true)
	public SmsCode getMobileMsg(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "1:注册 2:忘记密码 3:验证码登陆,绑定手机", required = true) Integer type,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(hidden = true) HttpServletRequest request)
			throws Exception {

		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (type == null) {
			throw new ApiException("type");
		}
		// 查询
		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(phone);

		String key;
		
		if (type == MobileMsgEnum.REGIST.getCode()) {// 注册
			int count = userService.countByExample(example);
			if (count > 0) {
				throw new ApiException(MEnumError.PHONE_EXISTS_ERROR2);
			}
			key = MobileMsgEnum.REGIST.getPhone(phone);
		} else if (type == MobileMsgEnum.FORGET.getCode()) {
			int count = userService.countByExample(example);
			if (count == 0) {
				throw new ApiException(MEnumError.PHONE_NOTEXISTS_ERROR);
			}
			key = MobileMsgEnum.FORGET.getPhone(phone);
		}else if (type == MobileMsgEnum.LOGIN.getCode()) {
			key = MobileMsgEnum.LOGIN.getPhone(phone);
		}else {
			throw new ApiException(-1,"参数错误");
		}

		// 发送短信
		String mobileCode = StringUtil.getRandomNum(6);
		//您的验证码是#code#
		//String content = new String("您的验证码是" + mobileCode);
		String result = "";
		if(type == 2){
			//忘记密码
			result += smsSendLogService.sendIdentifySms(phone,deviceid,IPUtil.getClientIP(request),"亲，您申请了密码找回服务，验证码为："+mobileCode+"，请尽快完成密码重置",type);
		}else{
			result += smsSendLogService.sendIdentifySms(phone,deviceid,IPUtil.getClientIP(request),"亲，您的验证码是："+mobileCode+"。请不要把验证码泄露给其他人。",type);
		}

		//String result = smsSendLogService.sendIdentifySms(phone,deviceid,IPUtil.getClientIP(request),content,null);
		if (StringUtil.equals("2",result)) {
			// 发送成功
			SmsCache.putCache(key,mobileCode);
//			CacheSupport.put("mobileCodeCache", key, mobileCode);
		} else {
			LogKit.debug(result);
			String error = SmsError.getSmsError(result);
			if (StringUtil.isNotBlank(error)){
				throw new ApiException(MEnumError.SMS_ERROR.getErrorCode(),
						error);
			}else if(StringUtil.isNotBlank(result)){
				throw new ApiException(MEnumError.SMS_ERROR.getErrorCode(),
						result);
			}else{
				throw new ApiException(MEnumError.SMS_ERROR);
			}
		}

		SmsCode ret = new SmsCode();
		if (!"true".equals(PropertySupport.getProperty("sms.enable"))){
			ret.setCode(mobileCode + "");
		}else{
			//测试
			ret.setCode("");
		}
		return ret;
	}

	/**
	 * 验证验证码
	 * 
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 */
	@ApiOperation(value = "验证验证码", notes = "不需要登录")
	@RequestMapping(value = "/checkCode", method = RequestMethod.POST)
	@ApiMethod
	public Ret checkCode(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "验证码", required = true) String code)
			throws Exception {
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(code)) {
			throw new ApiException("code");
		}
		// 验证码验证
		String value = SmsCache.getCache(MobileMsgEnum.REGIST.getPhone(phone));
//		String value = CacheSupport.get("mobileCodeCache", MobileMsgEnum.REGIST.getPhone(phone), String.class);

		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		}
		Ret ret = new Ret();
		ret.setCode(0);

		return ret;
	}

	/**
	 * 验证昵称
	 * 
	 * @param nickName
	 *            昵称
	 */
	@ApiOperation(value = "验证昵称", notes = "不需要登录")
	@RequestMapping(value = "/checkNick", method = RequestMethod.POST)
	@ApiMethod
	public Ret checkNick(
			@ApiParam(value = "昵称", required = true) String nickName)
			throws Exception {
		if (StringUtil.isBlank(nickName)) {
			throw new ApiException("nickName");
		}
		UserExample example = new UserExample();
		example.createCriteria().andNickNameEqualTo(nickName);
		int i = userService.countByExample(example);
		if (i > 0) {
			throw new ApiException(MEnumError.NICK_EXISTS_ERROR);
		}
		Ret ret = new Ret();
		ret.setCode(0);

		return ret;
	}

	/**
	 * 注册
	 * 
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @param password
	 *            密码(需要加密)
	 * @param deviceType
	 *            //设备类型 1:android 2:ios
	 * @param cid
	 *            //推送cid
	 */
	@ApiOperation(value = "注册", notes = "不需要登录")
	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	@ApiMethod
	public MobileInfo regist(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "验证码", required = true) String code,
			@ApiParam(value = "密码(需要MD5加密)", required = true) String password,
//			@ApiParam(value = "昵称", required = true) String nickName,
			@ApiParam(value = "设备类型 0:网页1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid)
			throws Exception {

		// 参数校验
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(code)) {
			throw new ApiException("code");
		}
		if (StringUtil.isBlank(password)) {
			throw new ApiException("password");
		}
//		if (StringUtil.isBlank(nickName)) {
//			throw new ApiException("nickName");
//		}

		if (deviceType == null) {
			throw new ApiException("deviceType");
		}

		if (deviceType != 0){
			if (StringUtil.isBlank(deviceid)) {
				throw new ApiException("deviceid");
			}
		}

		// 验证码验证
//		String value = CacheSupport.get("mobileCodeCache", MobileMsgEnum.REGIST.getPhone(phone), String.class);
		String value = SmsCache.getCache(MobileMsgEnum.REGIST.getPhone(phone));
		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		} else {
			SmsCache.delCache(MobileMsgEnum.REGIST.getPhone(phone));
//			CacheSupport.remove("mobileCodeCache", phone);
		}

		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(phone);
		int i = userService.countByExample(example);
		if (i > 0) {
			throw new ApiException(MEnumError.PHONE_EXISTS_ERROR);
		}

//		example.clear();
//		example.createCriteria().andNickNameEqualTo(nickName);
//		i = userService.countByExample(example);
//		if (i > 0) {
//			throw new ApiException(MEnumError.NICK_EXISTS_ERROR);
//		}

		User record = userService.regist(phone, password,
				phone);


		MobileInfo mobileInfo = new MobileInfo();
		mobileInfo.setUserid(record.getId());
		mobileInfo.setDeviceid(deviceid);
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setDeviceType(deviceType);
		mobileInfo.setToken(verify);
		mobileInfo.setHeadImg("");
		mobileInfo.setAccount(record.getAccount());
		return mobileInfo;
	}

	/**
	 * @api 密码登录
	 * @param phone
	 *            手机号
	 * @param password
	 *            密码(需要加密)
	 * @param deviceType
	 *            设备类型 1:android 2:ios
	 * @param cid
	 *            //推送cid
	 */
	@ApiOperation(value = "密码登录")
	@RequestMapping(value = "/loginByPwd", method = RequestMethod.POST)
	@ApiMethod
	public MobileInfo loginByPwd(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "密码(需要MD5加密)", required = true) String password,
			@ApiParam(value = "设备类型 0:网页1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码(app必填)", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid)
			throws Exception {
		// 参数校验
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(password)) {
			throw new ApiException("password");
		}
		if (deviceType == null) {
			throw new ApiException("deviceType");
		}
		if(deviceType!=0){
			if (StringUtil.isBlank(deviceid)) {
				throw new ApiException("deviceid");
			}
		}

		// 校验登录
		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(phone);
		List<User> list = userService.selectByExample(example);
		if (list.size() == 0) {
			throw new ApiException(MEnumError.LOGIN_FAILURE_ERROR);
		}
		User user = list.get(0);
		if (!password.equals(user.getPassword())) {
			throw new ApiException(MEnumError.LOGIN_FAILURE_ERROR);
		}
//		// 禁用
//		if (user.getState() == 0) {
//			throw new ApiException(MEnumError.ACCOUNT_STOP_ERROR);
//		}
		MobileInfo mobileInfo = new MobileInfo();
		mobileInfo.setUserid(user.getId());
		mobileInfo.setDeviceid(deviceid);
		mobileInfo.setDeviceType(deviceType);
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setToken(verify);
		if(user.getUserState() == 1 && user.getIsVerify() == 1){
			//艺术家
			mobileInfo.setHeadImg(user.getArtImg());
			mobileInfo.setNickName(user.getUserName());
			mobileInfo.setUserState(1);
		}else{
			//普通用户
			mobileInfo.setHeadImg(user.getHeadImg() == null? "" : user.getHeadImg());
			mobileInfo.setNickName(user.getNickName());
			mobileInfo.setUserState(0);
		}
		mobileInfo.setAccount(user.getAccount());
		if(user.getIsVip() == 0){
			mobileInfo.setIsVip(0);
		}else{
			user.setIsVip(1);
		}

		return mobileInfo;
	}

	/**
	 * @api 短信登录
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @param deviceType
	 *            设备类型 1:android 2:ios
	 * @param cid
	 *            //推送cid
	 */
	@ApiOperation(value = "短信登录")
	@RequestMapping(value = "/loginByCode", method = RequestMethod.POST)
	@ApiMethod
	public MobileInfo loginByCode(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "验证码", required = true) String code,
			@ApiParam(value = "设备类型 0:h5 1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid)
			throws Exception {
		// 参数校验
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(code)) {
			throw new ApiException("code");
		}
		if (deviceType == null) {
			throw new ApiException("deviceType");
		}
		if (deviceType != 0){
			if (StringUtil.isBlank(deviceid)) {
				throw new ApiException("deviceid");
			}
		}

		// 验证码验证
//		String value = CacheSupport.get("mobileCodeCache", MobileMsgEnum.LOGIN.getPhone(phone), String.class);
		String value = SmsCache.getCache(MobileMsgEnum.LOGIN.getPhone(phone));
		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		} else {
			SmsCache.delCache(MobileMsgEnum.LOGIN.getPhone(phone));
//			CacheSupport.remove("mobileCodeCache", phone);
		}

		// 校验登录
		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(phone);
		List<User> list = userService.selectByExample(example);
		User user;
		if (list.size() == 0) {
			user = userService.regist(phone, null,
					StringUtil.formatPhone(phone));
		} else {
			user = list.get(0);
		}

		// 禁用
//		if (user.getState() == 0) {
//			throw new ApiException(MEnumError.ACCOUNT_STOP_ERROR);
//		}

		MobileInfo mobileInfo = new MobileInfo();
		mobileInfo.setUserid(user.getId());
		mobileInfo.setDeviceid(deviceid);
		mobileInfo.setDeviceType(deviceType);
		if(user.getUserState() == 1 && user.getIsVerify() == 1){
			//艺术家
			mobileInfo.setHeadImg(user.getArtImg());
			mobileInfo.setNickName(user.getUserName());
			mobileInfo.setUserState(1);
		}else{
			//普通用户
			mobileInfo.setHeadImg(user.getHeadImg() == null? "" : user.getHeadImg());
			mobileInfo.setNickName(user.getNickName());
			mobileInfo.setUserState(0);
		}
		mobileInfo.setAccount(user.getAccount());
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setToken(verify);

		return mobileInfo;
	}

	/**
	 * 忘记密码
	 * 
	 * @param phone
	 *            手机号
	 * @param code
	 *            验证码
	 * @param password
	 *            密码(需要加密)
	 * @param deviceType
	 *            //设备类型 1:android 2:ios
	 * @param cid
	 *            //推送cid
	 */
	@ApiOperation(value = "忘记密码")
	@RequestMapping(value = "/forgetPwd", method = RequestMethod.POST)
	@ApiMethod
	public MobileInfo forgetPwd(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "验证码", required = true) String code,
			@ApiParam(value = "密码(需要加密)", required = true) String password,
			@ApiParam(value = "设备类型 0:网页 1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid)
			throws Exception {
		// 参数校验
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(code)) {
			throw new ApiException("code");
		}
		if (deviceType == null) {
			throw new ApiException("deviceType");
		}

		if (deviceType != 0){
			if (StringUtil.isBlank(deviceid)) {
				throw new ApiException("deviceid");
			}
		}
		// 验证码验证
//		String value = CacheSupport.get("mobileCodeCache", MobileMsgEnum.FORGET.getPhone(phone), String.class);
		String value = SmsCache.getCache(MobileMsgEnum.FORGET.getPhone(phone));
		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		} else {
			SmsCache.delCache(MobileMsgEnum.FORGET.getPhone(phone));
//			CacheSupport.remove("mobileCodeCache", phone);
		}

		// 修改数据
		UserExample uexample = new UserExample();
		uexample.createCriteria().andAccountEqualTo(phone);
		List<User> list = userService.selectByExample(uexample);

		if (list.size() == 0) {
			throw new ApiException(MEnumError.PHONE_NOTEXISTS_ERROR);
		}

		User record = list.get(0);
		record.setPassword(password);
		int cnt = userService.updateByPrimaryKeySelective(record);
		if (cnt == 0) {
			throw new ApiException(MEnumError.UPDATE_ACCOUNT_ERROR);
		}
		

		MobileInfo mobileInfo = new MobileInfo();
		mobileInfo.setUserid(record.getId());
		mobileInfo.setDeviceType(deviceType);
		mobileInfo.setDeviceid(deviceid);


		//删除其他登陆设备
		verifyService.deleteOther(mobileInfo);
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setToken(verify);
		//mobileInfo.setIsComplete(record.getIsComplete());
		return mobileInfo;
	}

	@ApiOperation(value = "第三方登录")
	@RequestMapping(value = "/oauthLogin", method = RequestMethod.POST)
	@ApiMethod
	public OauthMobileInfo oauthLoginNew(
			@ApiParam(value = "1:qq 2:sina 3:wx", required = true) Integer type,
			@ApiParam(value = "openid", required = true) String openid,
			@ApiParam(value = "accessToken", required = true) String accessToken,
			@ApiParam(value = "设备类型 1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid){
		// 参数校验
		if (type == null) {
			throw new ApiException("type");
		}
		if (StringUtil.isBlank(openid)) {
			throw new ApiException("openid");
		}
		if (deviceType == null) {
			throw new ApiException("deviceType");
		}
		if (StringUtil.isBlank(deviceid)) {
			throw new ApiException("deviceid");
		}
		UserOauthExample example = new UserOauthExample();
		example.createCriteria().andTypeEqualTo(type).andOpenIdEqualTo(openid);
		List<UserOauth> list = oauthService.selectByExample(example);
		OauthMobileInfo mobileInfo = new OauthMobileInfo();

		boolean insert = false;// 是否需要添加
		User user = null;
		if (list.size() == 0){
			insert = true;
		}else{
			UserOauth oauth = list.get(0);
			user = userService.selectByPrimaryKey(oauth.getUserId());
			if (user == null) {
				oauthService.deleteByPrimaryKey(oauth.getId());
				return mobileInfo;
			}
		}

		if (insert){
			OauthUserInfo oauthUserInfo = OauthLoginUtil.getOauthUserInfo(type, accessToken, openid);
			if (oauthUserInfo == null){
				throw new ApiException(MEnumError.OAUTH_INFO_ERROR);
			}

			String accout = oauthService.getOauthAccount(type);
			//user = userService.regist(accout,null,oauthUserInfo.getNickName(),fileService.uploadHeadImg(oauthUserInfo.getHeadImg()));
			user = new User();
			user.setAccount(accout);
			user.setPassword(null);
			user.setNickName(oauthUserInfo.getNickName());
			user.setIsVip(0);
			user.setSex(0);
			user.setUserType(1);
			user.setCredit(0);
			user.setUserState(0);
			user.setHeadImg(fileService.uploadHeadImg(oauthUserInfo.getHeadImg()));
			user.setIsVerify(0);
			userService.insertSelective(user);


			User record = new User();
			record.setId(user.getId());
			userService.updateByPrimaryKeySelective(record);


			UserOauth oauth = new UserOauth();
			oauth.setAccessToken(accessToken);
			oauth.setCreateTime(new Date());
			oauth.setOpenId(openid);
			oauth.setType(type);
			oauth.setUserId(user.getId());
			oauthService.insert(oauth);
		}


		mobileInfo.setSuccessLogin(1);
		mobileInfo.setUserid(user.getId());
		mobileInfo.setDeviceType(deviceType);
		mobileInfo.setDeviceid(deviceid);
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setToken(verify);
		mobileInfo.setHeadImg(user.getHeadImg());
		mobileInfo.setNickName(user.getNickName());
		//mobileInfo.setIsComplete(user.getIsComplete());
		return mobileInfo;
	}

	@ApiOperation(value = "第三方登录绑定手机号")
	@RequestMapping(value = "/oauthLoginBind", method = RequestMethod.POST)
	@ApiMethod
	public MobileInfo oauthLoginBindPhone(
			@ApiParam(value = "手机号", required = true) String phone,
			@ApiParam(value = "验证码", required = true) String code,
			@ApiParam(value = "1:qq 2:sina 3:wx", required = true) Integer type,
			@ApiParam(value = "openid", required = true) String openid,
			@ApiParam(value = "accessToken", required = true) String accessToken,
			@ApiParam(value = "设备类型 1:android 2:ios", required = true) Integer deviceType,
			@ApiParam(value = "设备唯一识别码", required = false) String deviceid,
			@ApiParam(value = "推送cid", required = false) String cid){
		if (StringUtil.isBlank(phone)) {
			throw new ApiException("phone");
		}
		if (StringUtil.isBlank(code)) {
			throw new ApiException("code");
		}
		// 参数校验
		if (type == null) {
			throw new ApiException("type");
		}
		if (StringUtil.isBlank(openid)) {
			throw new ApiException("openid");
		}
		if (deviceType == null) {
			throw new ApiException("deviceType");
		}
		if (StringUtil.isBlank(deviceid)) {
			throw new ApiException("deviceid");
		}
		// 验证码验证
//		String value = CacheSupport.get("mobileCodeCache", MobileMsgEnum.LOGIN.getPhone(phone), String.class);
		String value = SmsCache.getCache(MobileMsgEnum.LOGIN.getPhone(phone));
		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		} else {
			SmsCache.delCache(MobileMsgEnum.LOGIN.getPhone(phone));
//			CacheSupport.remove("mobileCodeCache", phone);
		}

		UserOauthExample example = new UserOauthExample();
		example.createCriteria().andTypeEqualTo(type).andOpenIdEqualTo(openid);
		List<UserOauth> list = oauthService.selectByExample(example);
		MobileInfo mobileInfo = new MobileInfo();
		if (list.size() > 0){
			throw new ApiException(-1,"账号已被绑定");
		}
		UserExample userExample = new UserExample();
		userExample.createCriteria().andAccountEqualTo(phone);
		List<User> users = userService.selectByExample(userExample);
		User user;
		if (users.size() == 0){
			user = userService.regist(phone, null, phone);
			// 第三方登陆获取头像昵称-第一次
//			if (StringUtil.isNotBlank(accessToken)) {
//				ThreadUtil.execute(new OauthLoginRunnable(user
//						.getId(), type, deviceType, openid, accessToken, userService));
//			}
		}else{
			user = users.get(0);
//			if (user.getState() == 0) {
//				throw new ApiException(MEnumError.ACCOUNT_STOP_ERROR);
//			}
		}

		User bind = new User();
		bind.setId(user.getId());
		switch (type){
			case 1:
				if (user.getIsBindQq() == 1){
					throw new ApiException(-1,"已绑定QQ");
				}
				bind.setIsBindQq(1);
				break;
			case 2:
				if (user.getIsBindWeibo() == 1){
					throw new ApiException(-1,"已绑定weibo");
				}
				bind.setIsBindWeibo(1);
				break;
			case 3:
				if (user.getIsBindWeixin() == 1){
					throw new ApiException(-1,"已绑定微信");
				}
				bind.setIsBindWeixin(1);
				break;
			default:
				throw new ApiException(-1,"类型错误1:qq 2:sina 3:wx");
		}

		UserOauth oauth = new UserOauth();
		oauth.setAccessToken(accessToken);
		oauth.setOpenId(openid);
		oauth.setUserId(user.getId());
		oauth.setType(type);
		oauthService.insert(oauth);

		userService.updateByPrimaryKeySelective(bind);

		mobileInfo.setUserid(user.getId());
		mobileInfo.setDeviceType(deviceType);
		mobileInfo.setDeviceid(deviceid);
		String verify = verifyService.updateMobileVerify(mobileInfo,
				deviceType, cid);
		mobileInfo.setToken(verify);

		return mobileInfo;
	}

	@ApiOperation(value = "第三方绑定",notes = "登陆")
	@RequestMapping(value = "/oauthBind", method = RequestMethod.POST)
	@ApiMethod(isLogin = true)
	public Ret oauthBind(MobileInfo mobileInfo,
									 @ApiParam(value = "1:qq 2:sina 3:wx", required = true) Integer type,
									 @ApiParam(value = "openid", required = true) String openid,
									 @ApiParam(value = "accessToken", required = true) String accessToken){
		// 参数校验
		if (type == null) {
			throw new ApiException("type");
		}
		if (StringUtil.isBlank(openid)) {
			throw new ApiException("openid");
		}
		UserOauthExample example = new UserOauthExample();
		example.createCriteria().andTypeEqualTo(type).andOpenIdEqualTo(openid);
		int cnt = oauthService.countByExample(example);
		if (cnt > 0){
			throw new ApiException(-1,"第三方账号已被绑定");
		}
		example.clear();
		example.createCriteria().andUserIdEqualTo(mobileInfo.getUserid()).andTypeEqualTo(type);
		cnt = oauthService.countByExample(example);
		if (cnt > 0){
			throw new ApiException(-1,"账号已绑定第三方账号");
		}
//		User bind = new User();
//		bind.setId(mobileInfo.getUserid());
		User bind = userService.selectByPrimaryKey(mobileInfo.getUserid());
		switch (type){
			case 1:
				bind.setIsBindQq(1);
				break;
			case 2:
				bind.setIsBindWeibo(1);
				break;
			case 3:
				bind.setIsBindWeixin(1);
				break;
			default:
				throw new ApiException(-1,"类型错误1:qq 2:sina 3:wx");
		}

		/*if(1 == bind.getIsBindWeibo() || 1 == bind.getIsBindWeixin()){
			//绑定微博或者微信
			//查询积分日志表是否已经增加这条记录
			CreditLogExample creditLogExample = new CreditLogExample();
			creditLogExample.createCriteria().andUserIdEqualTo(bind.getId()).andCreditCodeEqualTo(MYjyEnmu.bind_wxOrweibo.getName());

			List<CreditLog> list = creditLogService.selectByExample(creditLogExample);
			if(0 == list.size()){
				//没有这条记录
				//积分加10分--并且加入积分log表
				CreditLog creditLog = new CreditLog();
				creditLog.setCreditCode(MYjyEnmu.bind_wxOrweibo.getName());
				creditLog.setCreditNum(MYjyConstant.bind_wxOrweibo+"");
				creditLog.setType(1);
				creditLogService.insert(creditLog);

				//user表更新credit
				int credit = bind.getCredit() == null? 0 : bind.getCredit();
				bind.setCredit(credit + MYjyConstant.bind_wxOrweibo);
			}
		}
		userService.updateByPrimaryKeySelective(bind);*/

		UserOauth oauth = new UserOauth();
		oauth.setAccessToken(accessToken);
		oauth.setOpenId(openid);
		oauth.setUserId(mobileInfo.getUserid());
		oauth.setType(type);
		oauthService.insert(oauth);

		return ok();
	}

	@ApiOperation(value = "第三方登录解绑")
	@RequestMapping(value = "/oauthLoginUnBind", method = RequestMethod.POST)
	@ApiMethod(isLogin = true)
	public Ret unBindOauth(MobileInfo mobileInfo,
						   @ApiParam(value = "1:qq 2:sina 3:wx", required = true) Integer type){
		if (type == null){
			throw new ApiException("type");
		}
		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
		User bind = new User();
		bind.setId(mobileInfo.getUserid());
		switch (type){
			case 1:
				if (user.getIsBindQq() == 0){
					throw new ApiException(-1,"未绑定QQ");
				}
				bind.setIsBindQq(0);
				break;
			case 2:
				if (user.getIsBindWeibo() == 0){
					throw new ApiException(-1,"未绑定weibo");
				}
				bind.setIsBindWeibo(0);
				break;
			case 3:
				if (user.getIsBindWeixin() == 0){
					throw new ApiException(-1,"未绑定微信");
				}
				bind.setIsBindWeixin(0);
				break;
			default:
				throw new ApiException(-1,"类型错误1:qq 2:sina 3:wx");
		}

		UserOauthExample example = new UserOauthExample();
		example.createCriteria().andUserIdEqualTo(mobileInfo.getUserid()).andTypeEqualTo(type);
		oauthService.deleteByExample(example);
		userService.updateByPrimaryKeySelective(bind);
		return ok();
	}

	/**
	 * 修改密码
	 * 
	 * @param oldPwd
	 *            旧密码(需要加密)
	 * @param newPwd
	 *            新密码(需要加密)
	 */

	/**
	 * 注销
	 */
	@ApiOperation(value = "注销*", notes = "")
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ApiMethod(isLogin = true)
	@ApiUnCheck
	public Ret logout(MobileInfo mobileInfo) throws Exception {
		verifyService.logout(mobileInfo);
		return new Ret();
	}

	/**
	 * @api 绑定手机
	 * @param phone
	 *            手机号
	 * @param password
	 *            密码
	 * @param code
	 *            短信验证码
	 */


	/**
	 * 修改个人资料
	 * */
	@ApiOperation(value = "完善个人资料*",notes="登陆")
	@RequestMapping(value="/editUser", method = RequestMethod.POST)
	@ApiMethod(isLogin = true)
	@ApiUnCheck
	public UserInfo editUser(MobileInfo mobileInfo, UserInfo userInfo){
		if (StringUtil.isBlank(userInfo.getNickName())){
			throw new ApiException("nickName");
		}
		if (StringUtil.isBlank(userInfo.getHeadImg())){
			throw new ApiException("headImg");
		}
		if (userInfo.getSex() == null){
			throw new ApiException("sex");
		}
		if (StringUtil.isBlank(userInfo.getBirthday())){
			throw new ApiException("birthday");
		}

		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());

		User temp = new User();
		temp.setId(mobileInfo.getUserid());
		temp.setHeadImg(userInfo.getHeadImg());
		temp.setSex(userInfo.getSex());
		temp.setBirthday(userInfo.getBirthday());
		if(StringUtil.isNotBlank(userInfo.getArea())){
			temp.setArea(userInfo.getArea());
		}
		if(StringUtil.isNotBlank(userInfo.getJob())){
			temp.setJob(userInfo.getJob());
		}
		if(StringUtil.isNotBlank(userInfo.getSign())){
			temp.setSign(userInfo.getSign());
		}

		userInfo.setId(mobileInfo.getUserid());

		if (StringUtil.isNotBlank(userInfo.getNickName())){
			// 校验登录
			UserExample example = new UserExample();
			example.createCriteria().andNickNameEqualTo(userInfo.getNickName()).andIdNotEqualTo(mobileInfo.getUserid());
			int i = userService.countByExample(example);
//			if (i > 0) {
//				throw new ApiException(MEnumError.NICK_EXISTS_ERROR);
//			}
			temp.setNickName(userInfo.getNickName());
		}

		//更新
		userService.updateByPrimaryKeySelective(temp);


		temp = userService.selectByPrimaryKey(mobileInfo.getUserid());
		if (temp != null)
			userInfo.setAccount(temp.getAccount());
		return userInfo;
	}

	/**
	 * 绑定手机号
	 * */
	@ApiOperation(value = "绑定手机号*",notes="登陆")
	@RequestMapping(value="/bindPhone", method = RequestMethod.POST)
	@ApiMethod(isLogin = true)
	@ApiUnCheck
	public Ret bindPhone(MobileInfo mobileInfo,
							  @ApiParam(value = "短信验证码", required = true) String code,
							  @ApiParam(value = "需要绑定的手机号", required = true) String phone){
		UserExample example = new UserExample();
		example.createCriteria().andBindPhoneEqualTo(phone);
		int count = userService.countByExample(example);
		if(count > 1){
			throw new ApiException(-1,"该手机号已被绑定");
		}

		String value = SmsCache.getCache(MobileMsgEnum.LOGIN.getPhone(phone));
		if (!code.equals(value)) {
			throw new ApiException(MEnumError.MOBILE_CODE_ERROR);
		} else {
			SmsCache.delCache(MobileMsgEnum.LOGIN.getPhone(phone));
		}

		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());

		if(user.getIsBindPhone() != null && user.getIsBindPhone() == 1){
			throw new ApiException(-1,"已绑定手机号");
		}

		user.setIsBindPhone(1);
		user.setBindPhone(phone);
		userService.updateByPrimaryKeySelective(user);
		return new Ret(1);
	}
}
